package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.Result;
import com.itheima.youdianda.domain.*;
import com.itheima.youdianda.dto.qiantaiDto.YddArticlesDto;
import com.itheima.youdianda.service.YddArticleService;
import com.itheima.youdianda.service.YddCateService;
import com.itheima.youdianda.service.YddUserDataService;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author pk
 * @date 2022/09/07/14:15
 */
@RestController
@RequestMapping("/frame/user")
@Slf4j
public class UserController {

    @Autowired
    private YddUserDataService userDataService;
    @Autowired
    private YddArticleService articleService;
    @Autowired
    private YddUserService yddUserService;

    @Autowired
    private YddCateService cateService;


    //登录后首页
    @GetMapping("/getUserInfo")
    public Result getUserInfo(HttpSession session) {
        YddUser yddUser = yddUserService.getById((String)session.getAttribute("userId"));
        String username = yddUser.getUsername();

        //记录收藏
        LambdaQueryWrapper<YddUserData> yddUserDataLqw = new LambdaQueryWrapper<>();
        yddUserDataLqw.eq(YddUserData::getUserId, yddUser.getId());
        yddUserDataLqw.eq(YddUserData::getType, 1);
        int collectNum = (int) userDataService.count(yddUserDataLqw);
        //点赞
        LambdaQueryWrapper<YddUserData> yddUserDataLqw2 = new LambdaQueryWrapper<>();
        yddUserDataLqw2.eq(YddUserData::getUserId, yddUser.getId()).eq(YddUserData::getType, 2);
        int zanNum = (int) userDataService.count(yddUserDataLqw2);
        //文章
        LambdaQueryWrapper<YddArticle> articleLqw = new LambdaQueryWrapper<>();
        articleLqw.eq(YddArticle::getAuthor, username);
        int articleNum = (int) articleService.count(articleLqw);

        HashMap<String, Object> Map = new HashMap<>();
        Map.put("articleNum", articleNum);
        Map.put("collectNum", collectNum);
        Map.put("zanNum", zanNum);
        Map.put("userInfo", yddUser);
        log.info("{}", Map);
        return Result.ok(Map);
    }

    /**
     * 我的文章
     *
     * @return
     */
    @GetMapping("/myArticle")
    public Result myArticle(HttpSession session, Integer page, Integer limit) {

        Page pageInfo = new Page(page, limit);
        Integer userId = Integer.parseInt((String) session.getAttribute("userId"));

        //条件构造器
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getUserId, userId);

        articleService.page(pageInfo, lqw);

        //创建map集合容器
        HashMap<String, Object> map = new HashMap<>();
        map.put("count",pageInfo.getTotal());
        map.put("totalPages",pageInfo.getPages());
        map.put("pageSize",limit);
        map.put("currentPage",page);
        List<YddArticle> records = pageInfo.getRecords();
        map.put("data",records);
        return Result.ok(map);

    }


    /**
     * 我的收藏/点赞
     *
     * @return
     */
    @GetMapping("/userDataList")
    public Result userDataList(HttpSession session, Integer page, Integer limit, YddUserData userData) {

        //获取用户id
        Integer userId = Integer.parseInt((String) session.getAttribute("userId"));
        //创建page对象
        Page pageInfo = new Page(page, limit);
        //条件构造器
        LambdaQueryWrapper<YddUserData> lqwUserData = new LambdaQueryWrapper<>();
        //判断查询类型1.收藏 2.点赞
        lqwUserData.eq(YddUserData::getType, userData.getType());
        //等值匹配用户id,
        lqwUserData.eq(YddUserData::getUserId, userId);
        //获取文章id
        List<YddUserData> list = userDataService.list(lqwUserData);
        List<Integer> articleIds = list.stream().map((item) -> {
            Integer articleId = item.getArticleId();
            return articleId;
        }).collect(Collectors.toList());
        articleIds.add(-1);
        //条件构造器查询文章
        LambdaQueryWrapper<YddArticle> lqwArticle = new LambdaQueryWrapper<>();
        lqwArticle.in(YddArticle::getId, articleIds);
        articleService.page(pageInfo, lqwArticle);
        //创建map集合容器
        HashMap<String, Object> map = new HashMap<>();
        map.put("count",pageInfo.getTotal());
        map.put("totalPages",pageInfo.getPages());
        map.put("pageSize",limit);
        map.put("currentPage",page);
        List<YddArticle> records = pageInfo.getRecords();
        List<YddArticlesDto> articlesDtos = records.stream().map((item) -> {
            YddArticlesDto articlesDto = new YddArticlesDto();
            BeanUtils.copyProperties(item, articlesDto);
            YddCate cate = cateService.getById(item.getCateid());
            if (cate != null) {
                articlesDto.setCatename(cate.getCatename());
            }
            return articlesDto;
        }).collect(Collectors.toList());
        map.put("data",articlesDtos);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("list",map);

        return Result.ok(stringObjectHashMap);
    }


    /**
     * 点赞/取消点赞
     * 收藏/取消收藏
     *
     * @return
     */
    @GetMapping("/userDataHandle")
    public Result userDataHandle(HttpSession session, String action, Integer type, Integer article_id) {
        userDataService.updateWithAction(session, action, type, article_id);

        return Result.ok("操作成功");
    }


    /**
     * 修改文章
     *
     * @param yddArticle
     * @return
     */
    @PostMapping("/editArticle")
    public Result editArticle(@RequestBody YddArticle yddArticle) {
        LambdaUpdateWrapper<YddArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(YddArticle::getId, yddArticle.getId())
                .set(YddArticle::getStatus, yddArticle.getStatus());

        return Result.ok("修改成功");
    }

    /**
     * 修改个人信息
     *
     * @param
     * @param user
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody YddUser user) {
        //对password进行MD5加密
        String md5Pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pwd);
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtils.isEmpty(user.getUsername()), YddUser::getUsername, user.getUsername());
        YddUser yddUser = yddUserService.getOne(wrapper);
        if (!ObjectUtils.isEmpty(yddUser) && !yddUser.getId().equals(user.getId())) {
            return Result.error("用户名已存在");
        }
        yddUserService.updateById(user);
        return Result.ok("成功");
    }


    /**
     * 发布文章
     *
     * @return
     */
    @PostMapping("/addArticle")
    public Result addArticle(@RequestBody YddArticle yddArticle, HttpSession session) {
        Integer userId = Integer.parseInt((String) session.getAttribute("userId"));

        yddArticle.setUserId(userId);
        yddArticle.setAuthor(userId.toString());

        Date date = new Date();
        yddArticle.setCreateDate(date.getTime());

        articleService.save(yddArticle);

        return Result.ok("发布成功");
    }


}
